<template>
  <div>
    <!-- ========================= 生产报表 ========================= -->
    <div class="box-padding-16">
      <div class="box-padding-16-flex">
        <div class="box-padding-16-flex-left">
          <div class="line"></div>
          <div class="box-title">生产报表</div>
        </div>
        <div class="head">
          <el-radio-group v-model="range" size="mini" class="radio" @change="changeRange('prod')">
            <el-radio-button label="本月" />
            <el-radio-button label="本季" />
            <el-radio-button label="本年" />
          </el-radio-group>
        </div>
      </div>
      <div class="query">
        <el-form :model="queryParams" ref="prodForm" size="small" :inline="true">
          <el-form-item label="产品名称" prop="configName">
            <el-input v-model="queryParams.configName" placeholder="请输入参数名称" clearable style="width: 240px" />
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" class="w60" @click="searchProd">查询</el-button>
            <el-button size="mini" class="w60" @click="resetProd">重置</el-button>
            <el-button size="mini" class="w60" @click="export1">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="list" border size="mini" class="tbl" max-height="380">
        <!-- 固定列 -->
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="date" label="日期" align="center" />
        <el-table-column prop="总量" label="总量/吨" align="center" />

        <!-- 动态列 -->
        <el-table-column v-for="col in dynamicCols" :key="col.key" :prop="col.key" :label="col.label" align="center" />
      </el-table>
    </div>

    <!-- ========================= 销售报表 ========================= -->
    <div class="box-padding-16">
      <div class="box-padding-16-flex">
        <div class="box-padding-16-flex-left">
          <div class="line"></div>
          <div class="box-title">销售报表</div>
        </div>
        <div class="head">
          <el-radio-group v-model="saleRange" size="mini" class="radio" @change="changeRange('sale')">
            <el-radio-button label="本月" />
            <el-radio-button label="本季" />
            <el-radio-button label="本年" />
          </el-radio-group>
        </div>
      </div>
      <div class="query">
        <el-form ref="saleForm" size="small" :inline="true">
          <el-form-item label="时间">
            <el-date-picker v-model="dateRange1" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" class="w60" @click="searchSale">查询</el-button>
            <el-button size="mini" class="w60" @click="resetSale">重置</el-button>
            <el-button size="mini" class="w60" @click="export2">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="sale-container">
        <div class="sale-left">
          <el-table :data="saleList" border size="mini" class="tbl" max-height="273">
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column prop="date" label="日期" align="center" />
            <el-table-column prop="销售总量" label="销售总量" align="center" />

            <!-- 动态列 -->
            <el-table-column v-for="col in dynamicCols1" :key="col.key" :prop="col.key" :label="col.label"
              align="center" />
          </el-table>
        </div>
        <div class="sale-right">
          <el-table :data="saleDetailList" border size="mini" class="tbl" max-height="273">
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column prop="customerName" label="客户名称" align="center" />
            <el-table-column prop="product" label="产品" align="center" />
            <el-table-column prop="quantity" label="数量（吨）" align="center" />
          </el-table>
        </div>
      </div>
    </div>

    <!-- ========================= 设备报表 ========================= -->
    <div class="box-padding-16">
      <div class="box-padding-16-flex">
        <div class="box-padding-16-flex-left">
          <div class="line"></div>
          <div class="box-title">设备报表</div>
        </div>
        <div class="head">
          <el-radio-group v-model="devRange" size="mini" class="radio" @change="changeRange('dev')">
            <el-radio-button label="本月" />
            <el-radio-button label="本季" />
            <el-radio-button label="本年" />
          </el-radio-group>
        </div>
      </div>
      <div class="query">
        <el-form ref="devForm" size="small" :inline="true">
          <el-form-item label="时间">
            <el-date-picker v-model="dateRange2" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" class="w60" @click="searchDev">查询</el-button>
            <el-button size="mini" class="w60" @click="resetDev">重置</el-button>
            <el-button size="mini" class="w60" @click="export3">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="devList" border size="mini" class="tbl">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="deviceName" label="设备名称" align="center" />
        <el-table-column prop="deviceCode" label="设备编号" align="center" />
        <el-table-column prop="workshop" label="所属车间" align="center" />
        <el-table-column prop="runtimeHours" label="运行时长" align="center" width="140" />
        <el-table-column prop="alarmCount" label="告警次数" align="center" width="140" />
      </el-table>
    </div>
  </div>
</template>

<script>
import {
  productionreport,
  salesreport,
  customerlist,
  reportlist,
} from "@/api/home.js";
import * as XLSX from 'xlsx-js-style'; // 改为带样式的版本
import { saveAs } from 'file-saver';

// 中文标题映射
const LABEL_MAP = {
  "0-40mm": "0-40mm",
  "5-10mm": "5-10mm",
  "10-20mm": "10-20mm",
  "20-31.5mm": "20-31.5mm",
  "40—80mm": "40—80mm",
  收尘粉: "收尘粉",
  机制砂: "机制砂",
  毛石: "毛石",
};

const fmt = (d) => {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${dd}`;
};

// 通用导出工具函数
const exportUtils = {
  // 设置整个工作表居中对齐
  setCellCenter(ws) {
    const range = XLSX.utils.decode_range(ws['!ref']);
    for (let R = range.s.r; R <= range.e.r; ++R) {
      for (let C = range.s.c; C <= range.e.c; ++C) {
        const cellRef = XLSX.utils.encode_cell({ c: C, r: R });
        if (!ws[cellRef]) continue;
        
        // 添加样式
        ws[cellRef].s = {
          alignment: {
            horizontal: 'center',
            vertical: 'center'
          }
        };
      }
    }
  },
  
  // 将数据转换为工作表
  toSheet(data, columns) {
    const headers = columns.map(col => col.label);
    const rows = data.map(row => {
      return columns.map(col => {
        const value = row[col.key];
        return value === null || value === undefined ? '' : value;
      });
    });
    return [headers, ...rows];
  },
  
  // 创建并下载Excel文件
  download(workbook, fileName) {
    const excelBuffer = XLSX.write(workbook, {
      bookType: 'xlsx',
      type: 'array',
      bookSST: false
    });
    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
    saveAs(blob, fileName + '.xlsx');
  }
};

export default {
  name: "Report",
  data() {
    return {
      dynamicCols1: [],
      dynamicCols: [],
      columnMap: {},
      dateRange: [],
      dateRange1: [],
      dateRange2: [],
      queryParams: {},
      range: "本月",
      saleRange: "本月",
      devRange: "本月",
      list: [],
      saleList: [],
      saleDetailList: [],
      devList: [],
    };
  },
  created() {
    this.initRange();
    this.getAll();
  },
  methods: {
    /* -------------------- 通用日期计算 -------------------- */
    initRange() {
      this.dateRange = this.calcRange(this.range);
      this.dateRange1 = this.calcRange(this.saleRange);
      this.dateRange2 = this.calcRange(this.devRange);
    },
    calcRange(type) {
      const today = new Date();
      let startDate, endDate;
      switch (type) {
        case "本周":
          startDate = new Date(
            today.setDate(today.getDate() - today.getDay() + 1)
          );
          endDate = new Date(today.setDate(startDate.getDate() + 6));
          break;
        case "本月":
          startDate = new Date(today.getFullYear(), today.getMonth(), 1);
          endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
          break;
        case "本季":
          const q = Math.floor(today.getMonth() / 3);
          startDate = new Date(today.getFullYear(), q * 3, 1);
          endDate = new Date(today.getFullYear(), q * 3 + 3, 0);
          break;
        case "本年":
          startDate = new Date(today.getFullYear(), 0, 1);
          endDate = new Date(today.getFullYear(), 11, 31);
          break;
      }
      return [fmt(startDate), fmt(endDate)];
    },
    changeRange(module) {
      if (module === "prod") {
        this.dateRange = this.calcRange(this.range);
        this.searchProd();
      }
      if (module === "sale") {
        this.dateRange1 = this.calcRange(this.saleRange);
        this.searchSale();
      }
      if (module === "dev") {
        this.dateRange2 = this.calcRange(this.devRange);
        this.searchDev();
      }
    },

    /* -------------------- 查询 / 重置 -------------------- */
    searchProd() {
      const [startDate, endDate] = this.dateRange || [];
      productionreport({ ...this.queryParams, startDate, endDate }).then(
        (res) => {
          const cleaned = res.data.map((row) => {
            const obj = {};
            Object.keys(row).forEach((k) => {
              const safeKey = k.replace(/\./g, "_");
              obj[safeKey] = row[k];
            });
            return obj;
          });

          this.list = cleaned;
          this.buildDynamicCols(cleaned);
        }
      );
    },
    buildDynamicCols(arr) {
      if (!arr || !arr.length) return;
      const first = arr[0];
      const keys = Object.keys(first);
      const dynamicKeys = keys.filter((k) => !["date", "总量"].includes(k));

      this.dynamicCols = dynamicKeys.map((key) => ({
        key,
        label: LABEL_MAP[key.replace(/_/g, ".")] || key.replace(/_/g, "."),
      }));
    },
    resetProd() {
      this.$refs.prodForm.resetFields();
      this.queryParams = {};
      this.dateRange = this.calcRange(this.range);
      this.searchProd();
    },
    searchSale() {
      const [startDate, endDate] = this.dateRange1 || [];
      salesreport({ startDate, endDate }).then((res) => {
        const cleaned = res.data.map((row) => {
          const obj = {};
          Object.keys(row).forEach((k) => {
            const safeKey = k.replace(/\./g, "_");
            obj[safeKey] = row[k];
          });
          return obj;
        });

        this.saleList = cleaned;
        this.buildDynamicCols1(cleaned);
      });
      customerlist({ startDate, endDate }).then((res) => {
        this.saleDetailList = res.data;
      });
    },
    buildDynamicCols1(arr) {
      if (!arr || !arr.length) return;
      const first = arr[0];
      const keys = Object.keys(first);
      const dynamicKeys = keys.filter((k) => !["date", "销售总量"].includes(k));

      this.dynamicCols1 = dynamicKeys.map((key) => ({
        key,
        label: LABEL_MAP[key.replace(/_/g, ".")] || key.replace(/_/g, "."),
      }));
    },
    resetSale() {
      this.dateRange1 = this.calcRange(this.saleRange);
      this.searchSale();
    },
    searchDev() {
      const [startDate, endDate] = this.dateRange2 || [];
      reportlist({ startDate, endDate }).then((res) => {
        this.devList = res.data;
      });
    },
    resetDev() {
      this.dateRange2 = this.calcRange(this.devRange);
      this.searchDev();
    },

    /* -------------------- 导出功能实现（内容居中） -------------------- */
    // 导出生产报表
    export1() {
      if (!this.list || this.list.length === 0) {
        this.$message.warning('暂无数据可导出');
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: '正在导出生产报表...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        const columns = [
          { key: '__index', label: '序号' },
          { key: 'date', label: '日期' },
          { key: '总量', label: '总量/吨' },
          ...this.dynamicCols
        ];

        const dataWithIndex = this.list.map((row, index) => ({
          ...row,
          __index: index + 1
        }));

        const sheetData = exportUtils.toSheet(dataWithIndex, columns);
        const ws = XLSX.utils.aoa_to_sheet(sheetData);
        
        // 设置所有单元格居中对齐
        exportUtils.setCellCenter(ws);

        // 设置列宽
        ws['!cols'] = [
          { wch: 10 },
          { wch: 12 },
          { wch: 12 },
          ...this.dynamicCols.map(() => ({ wch: 12 }))
        ];

        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '生产报表');

        const fileName = `生产报表_${this.dateRange[0]}_${this.dateRange[1]}`;
        exportUtils.download(wb, fileName);
        
        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试');
      } finally {
        loading.close();
      }
    },

    // 导出销售报表
    export2() {
      if ((!this.saleList || this.saleList.length === 0) && 
          (!this.saleDetailList || this.saleDetailList.length === 0)) {
        this.$message.warning('暂无数据可导出');
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: '正在导出销售报表...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        const wb = XLSX.utils.book_new();

        // 导出销售汇总表
        if (this.saleList && this.saleList.length > 0) {
          const columns = [
            { key: '__index', label: '序号' },
            { key: 'date', label: '日期' },
            { key: '销售总量', label: '销售总量' },
            ...this.dynamicCols1
          ];

          const dataWithIndex = this.saleList.map((row, index) => ({
            ...row,
            __index: index + 1
          }));

          const sheetData = exportUtils.toSheet(dataWithIndex, columns);
          const ws1 = XLSX.utils.aoa_to_sheet(sheetData);
          
          // 设置所有单元格居中对齐
          exportUtils.setCellCenter(ws1);

          ws1['!cols'] = [
            { wch: 10 },
            { wch: 12 },
            { wch: 12 },
            ...this.dynamicCols1.map(() => ({ wch: 12 }))
          ];

          XLSX.utils.book_append_sheet(wb, ws1, '销售汇总');
        }

        // 导出销售明细表
        if (this.saleDetailList && this.saleDetailList.length > 0) {
          const columns = [
            { key: '__index', label: '序号' },
            { key: 'customerName', label: '客户名称' },
            { key: 'product', label: '产品' },
            { key: 'quantity', label: '数量（吨）' }
          ];

          const dataWithIndex = this.saleDetailList.map((row, index) => ({
            ...row,
            __index: index + 1
          }));

          const sheetData = exportUtils.toSheet(dataWithIndex, columns);
          const ws2 = XLSX.utils.aoa_to_sheet(sheetData);
          
          // 设置所有单元格居中对齐
          exportUtils.setCellCenter(ws2);

          ws2['!cols'] = [
            { wch: 10 },
            { wch: 20 },
            { wch: 15 },
            { wch: 12 }
          ];

          XLSX.utils.book_append_sheet(wb, ws2, '销售明细');
        }

        const fileName = `销售报表_${this.dateRange1[0]}_${this.dateRange1[1]}`;
        exportUtils.download(wb, fileName);
        
        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试');
      } finally {
        loading.close();
      }
    },

    // 导出设备报表
    export3() {
      if (!this.devList || this.devList.length === 0) {
        this.$message.warning('暂无数据可导出');
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: '正在导出设备报表...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        const columns = [
          { key: '__index', label: '序号' },
          { key: 'deviceName', label: '设备名称' },
          { key: 'deviceCode', label: '设备编号' },
          { key: 'workshop', label: '所属车间' },
          { key: 'runtimeHours', label: '运行时长' },
          { key: 'alarmCount', label: '告警次数' }
        ];

        const dataWithIndex = this.devList.map((row, index) => ({
          ...row,
          __index: index + 1
        }));

        const sheetData = exportUtils.toSheet(dataWithIndex, columns);
        const ws = XLSX.utils.aoa_to_sheet(sheetData);
        
        // 设置所有单元格居中对齐
        exportUtils.setCellCenter(ws);

        ws['!cols'] = [
          { wch: 10 },
          { wch: 15 },
          { wch: 15 },
          { wch: 15 },
          { wch: 12 },
          { wch: 12 }
        ];

        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '设备报表');

        const fileName = `设备报表_${this.dateRange2[0]}_${this.dateRange2[1]}`;
        exportUtils.download(wb, fileName);
        
        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试');
      } finally {
        loading.close();
      }
    },

    /* -------------------- 初始加载 -------------------- */
    getAll() {
      this.searchProd();
      this.searchSale();
      this.searchDev();
    },
  },
};
</script>

<style scoped>
/* =========  以下样式保持原文件不动  ========= */
.sale-container {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.sale-left {
  width: 65%;
}

.sale-right {
  width: 34%;
}

.box {
  padding: 12px 16px;
  background: #fff;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", SimSun, sans-serif;
}

.head {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: normal;
  color: #303133;
}

.radio {
  display: flex;
}

.query {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 16px;
}

.to {
  font-size: 12px;
  color: #606266;
  margin: 0 2px;
}

.w120 {
  width: 120px;
}

.w100 {
  width: 100px;
}

.w80 {
  width: 80px;
}

.w150 {
  width: 150px;
}

.w60 {
  width: 60px;
}

.tbl {
  margin-top: 10px;
}

.tbl>>>.el-table__body,
.tbl>>>.el-table__header {
  border-collapse: collapse;
}

.tbl>>>td,
.tbl>>>th {
  padding: 5px 0;
  font-size: 12px;
  height: 28px;
  line-height: 1;
}

.tbl>>>th {
  background: #f5f7fa;
  color: #606266;
  font-weight: normal;
}

.tbl>>>.cell {
  padding-left: 4px;
  padding-right: 4px;
}
</style>